package com.dk.demo.core.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dk.common.result.ApiPageResult;
import com.dk.common.utils.CommonUtils;
import com.dk.demo.common.model.FileInfoDTO;
import com.dk.demo.core.entity.FileInfoEntity;
import com.dk.demo.core.mapper.FileInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

@Service
public class FileInfoService extends ServiceImpl<FileInfoMapper, FileInfoEntity> {

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Transactional(rollbackFor = Exception.class)
    public Integer batchSave(List<FileInfoDTO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        List<FileInfoEntity> fileInfoEntities = list.stream().map(dto ->
                        CommonUtils.copyProperties(dto, FileInfoEntity.class))
                .toList();
        return fileInfoMapper.insertBatchSomeColumn(fileInfoEntities);
    }

    @Transactional(rollbackFor = Exception.class)
    public ApiPageResult<FileInfoDTO> page(Long datasetId) {
        LambdaQueryWrapper<FileInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper =  queryWrapper.eq(FileInfoEntity::getDatasetId, datasetId);
        Page<FileInfoEntity> page = new Page<>(0, 10);
       page = baseMapper.selectPage(page,queryWrapper);
        List<FileInfoDTO>content = page.getRecords().stream().map(this::convert).toList();
        return new ApiPageResult<>(content,Long.valueOf(page.getPages()).intValue(),page.getTotal());
    }

    @Transactional(rollbackFor = Exception.class)
    public List<FileInfoDTO> queryList(Long datasetId) {
        LambdaQueryWrapper<FileInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(FileInfoEntity::getDatasetId, datasetId);
        List<FileInfoEntity> fileInfoEntities = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(fileInfoEntities)) {
            return Collections.emptyList();
        }
        return fileInfoEntities.stream().map(this::convert).toList();
    }


    private  FileInfoDTO convert(FileInfoEntity entity) {
        return FileInfoDTO.builder()
                .fileName(entity.getFileName())
                .fileSize(entity.getFileSize())
                .datasetId(entity.getDatasetId())
                .build();
    }
}
